<template>
  <div class="storage-root">

    <el-row :gutter="10" class="mb8 s-header">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="back">
          返回
        </el-button>
      </el-col>
    </el-row>


    <el-table class="grass-table" v-loading="loading" :data="dataList" height="calc(100% - 120px)">

      <el-table-column type="index" width="50" label="序号"/>


      <el-table-column label="入库时间" align="center" prop="inTime">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.inTime" placement="top-start">
            <div class="s-t-item">{{ parseTime(scope.row.inTime, '{y}-{m}-{d}') }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="货架编号" align="center" prop="shelveId">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.shelveId == null?'':scope.row.shelveId.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.shelveId }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="入库时活性" align="center" prop="inActive">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark"
                      :content="scope.row.inActive == null?'':scope.row.inActive.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.inActive }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="入库量" align="center" prop="inAmount">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.inAmount==null?'':scope.row.inAmount.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.inAmount }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="入库登记人" align="center" prop="inUserId">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.inUserId==null?'':scope.row.inUserId.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.inUserId }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="千粒重" align="center" prop="inGrain">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.inGrain==null?'':scope.row.inGrain.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.inGrain }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="纯净度" align="center" prop="inPurity">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.inPurity==null?'':scope.row.inPurity.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.inPurity }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="活性时长" align="center" prop="activeDate">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark"
                      :content="scope.row.activeDate==null?'':scope.row.activeDate.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.activeDate }}</div>
          </el-tooltip>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="createRQ(scope.row)"
          >生成二维码
          </el-button>
        </template>
      </el-table-column>

    </el-table>


    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>


    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

      <div class="zz-sto-f-container">
        <el-scrollbar>
          <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">

            <el-form-item label="入库时间" prop="inTime">
              <el-date-picker
                v-model="form.inTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="货架编号" prop="shelveId">
              <el-cascader
                :options="shelveList"
                :props="{ checkStrictly: true , value:'id',label:'name'}"
                v-model="form.shelveId"
                clearable></el-cascader>
            </el-form-item>

            <el-form-item label="入库时活性" prop="inActive">
              <el-input v-model="form.inActive"/>
            </el-form-item>

            <el-form-item label="入库量" prop="inAmount">
              <el-input type="number" v-model="form.inAmount"/>
            </el-form-item>

            <el-form-item label="入库登记人" prop="inUserId">
              <el-input v-model="form.inUserId"/>
            </el-form-item>

            <el-form-item label="千粒重" prop="inGrain">
              <el-input v-model="form.inGrain"/>
            </el-form-item>

            <el-form-item label="纯净度" prop="inPurity">
              <el-input v-model="form.inPurity"/>
            </el-form-item>

            <el-form-item label="活性时长" prop="activeDate">
              <el-input v-model="form.activeDate">
                <template slot="append">年</template>
              </el-input>
            </el-form-item>

          </el-form>
        </el-scrollbar>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="二维码" :visible.sync="openQR" width="400px" append-to-body>
      <div class="zz-s-i-container">
        <img :src="codeUrl"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadQR">下 载</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, computed } from '@vue/composition-api'
  import { Message, MessageBox } from 'element-ui'
  import store from '@/store'
  import router from '@/router'
  import {
    addAutData, addStorageData,
    editAutData, editStorageData,
    exportAutData,
    getAutData,
    getAutListByCltId, getStorageData,
    getStorageList, qrCode
  } from '@/api/industry/lab'
  import { getField } from '@/api/field/field'
  import { shelveList } from '@/api/industry/gpm'
  import { handleTree } from '@/utils/mc'
  import { getPicUrl } from '@/api/industry/file'

  export default {
    props: {},
    components: {},
    setup(props, content) {

      let {} = props

      let { history: { current: { query: { cltId, germplasmId, labId, pageNum, pageSize, queryType, showType, proId } } } } = router

      const data = reactive({
        shelveList: [],
        open: false,
        showSearch: true,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          cltId
        },
        dataList: [],
        total: 0,
        loading: false,
        title: '',
        form: {
          cltId,
          inTime: null,
          shelveId: null,
          inActive: null,
          inAmount: null,
          inUserId: null,
          inGrain: null,
          inPurity: null,
          activeDate: null
        },
        rules: {
          inTime: [
            { required: true, message: '入库时间不能为空', trigger: 'blur' }
          ],
          shelveId: [
            { type: 'array', required: true, message: '货架编号不能为空', trigger: 'blur' }
          ],
          inActive: [
            { required: true, message: '入库时活性不能为空', trigger: 'blur' }
          ],
          inAmount: [
            { required: true, message: '入库量不能为空', trigger: 'blur' }
          ],
          inUserId: [
            { required: true, message: '入库登记人不能为空', trigger: 'blur' }
          ],
          inGrain: [
            { required: true, message: '千粒重不能为空', trigger: 'blur' }
          ],
          inPurity: [
            { required: true, message: '纯净度不能为空', trigger: 'blur' }
          ],
          activeDate: [
            { required: true, message: '活性时长不能为空', trigger: 'blur' }
          ]
        },
        openQR: false,
        currentShelve: null,
        baseShelveList: null,
        codeUrl: '',
        currentFileName: ''
      })

      const back = () => {
        router.push({ path: '/lab', query: { labId, pageNum, pageSize, queryType, showType, proId } })
      }

      // 表单重置
      const reset = () => {
        data.form = {
          cltId,
          inTime: null,
          shelveId: null,
          inActive: null,
          inAmount: null,
          inUserId: null,
          inGrain: null,
          inPurity: null,
          activeDate: null
        }
      }

      /** 新增按钮操作 */
      const handleAdd = () => {
        reset()
        data.open = true
        data.title = '新增入库数据'
      }

      /** 修改按钮操作 */
      const handleUpdate = row => {
        reset()
        const dtorageId = row.dtorageId
        getStorageData(dtorageId).then(response => {
          data.form = response.data
          data.open = true
          data.title = '修改入库数据'
          data.opne = true
        })
      }

      const getList = () => {
        data.loading = true
        getStorageList(data.queryParams).then(response => {
          data.dataList = response.rows.map(item => {
            item.germplasmId = germplasmId
            return item
          })
          data.total = response.total
          data.loading = false
        })
      }

      const submitForm = () => {
        content.refs.formRef.validate(async valid => {
          if (valid) {
            let { form } = data

            form.shelveId = form.shelveId[form.shelveId.length - 1]

            if (!verifyShelveType(form.shelveId)) {
              Message.error('请选择正确的货架类型')
              return
            }

            if (form.dtorageId != null) {
              await editStorageData(form)
            } else {
              await addStorageData(form)
            }
            data.open = false
            getList()
            reset()
          }
        })
      }

      // 取消按钮
      const cancel = () => {
        data.open = false
        reset()
      }

      //  生成二维码
      const createRQ = row => {
        qrCode({ dtorageId: row.dtorageId }).then(res => {
          data.codeUrl = `${getPicUrl}/${res.msg}`
          data.openQR = true
          data.currentFileName = res.msg
        })
      }

      //  获取货位数据
      const getShelveList = () => {
        shelveList().then(res => {
          data.baseShelveList = JSON.parse(JSON.stringify(res.data))
          data.shelveList = handleTree(res.data)
        })
      }

      const verifyShelveType = code => {
        let { baseShelveList } = data
        let currentItem = baseShelveList.find(item => item.id === code)
        return currentItem?.type === '6'
      }

      const downloadQR = () => {
        const element = document.createElement('a')
        let { codeUrl, currentFileName } = data
        fetch(codeUrl).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
          element.href = URL.createObjectURL(blob)
          document.body.appendChild(element)
          element.setAttribute('download', currentFileName)
          element.click()
        })
        element.style.display = 'none'
        element.remove()
      }

      getList()
      getShelveList()

      return { ...toRefs(data), back, handleAdd, getList, handleUpdate, cancel, submitForm, createRQ, downloadQR }
    }
  }
</script>

<style scoped lang="scss">
  $full: 100%;
  .storage-root {
    width: 100%;
    height: 100%;
    padding: 10px;

    .s-header {
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
    }

    .el-table {
      .el-table__body-wrapper {
        .el-table__body {
          .el-table__row {
            .cell {
              .s-t-item {
                width: 100%;
                height: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }
      }
    }


    .pagination-container {
      height: 53px;
    }
  }
</style>
<style lang="scss">
  .zz-sto-f-container {
    height: 400px;
  }

  .zz-s-i-container {
    height: 300px;
    width: 100%;
    display: flex;
    justify-content: center;
    flex-direction: row;
    align-content: center;
  }
</style>
